package com.zk.sqservice.service;

import android.os.MemoryFile;
import android.os.ParcelFileDescriptor;
import android.os.RemoteException;
import android.util.Log;

import com.zk.sqservice.ISqService;
import com.zk.sqservice.constant.DebugTag;
import com.zk.sqservice.util.MemoryFileHelper;

/**
 * @author zgx
 * //todo 服务代码
 **/
public class SqServiceStub extends ISqService.Stub {

    private static final String TAG = DebugTag.TAG;

    private byte[] mPackageContent;

    @Override
    public void basicTypes(int anInt, long aLong,
                           boolean aBoolean, float aFloat,
                           double aDouble, String aString)
            throws RemoteException {

    }

    @Override
    public void dataFlow(ParcelFileDescriptor data, int length) {
        Log.i(DebugTag.TAG, "SqServiceStub dataFlow ： onCreate pid = " + android.os.Process.myPid());

        try {
            long time = System.currentTimeMillis();
            createBufferIfNeed(length);
            MemoryFile memoryFile = MemoryFileHelper
                    .openMemoryFile(data, mPackageContent.length,
                            MemoryFileHelper.OPEN_READWRITE);
            memoryFile.readBytes(mPackageContent, 0, 0, mPackageContent.length);
            memoryFile.close();
            Log.d(TAG, "服务端读取 : " + mPackageContent[mPackageContent.length - 1]
                    + "，耗费时间 : " + (System.currentTimeMillis() - time));
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, "dataFlow err = " + e.toString());
        }
    }

    private void createBufferIfNeed(int length) {
        if (length <= 0) {
            Log.d(TAG, "createBufferIfNeed length <= 0");
        }
        if (mPackageContent != null && mPackageContent.length == length) {
            return;
        }
        mPackageContent = new byte[length];
    }
}
